const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');
Page({
  data: {
    // 学籍基础信息数据对象
    gk_academic_info: {
      city_code: '', // 盟市代码
      county_code: '', // 旗县代码
      registration_point_code: '', // 报名点代码
      graduate_type_id: '', // 毕业类别ID
      graduate_school_code: '', // 毕业中学代码，不唯一
      graduate_school_name: '', // 毕业中学名称，唯一
      graduate_class: '', // 毕业中学班号
      study_school_code: '', // 就读中学代码，不唯一
      study_school_name: '', // 就读中学名称，唯一
      study_class: '', // 就读中学班号
      registration_authority: '', // 户籍登记机关
      registered_residence_code: '', // 户口所在地代码，不唯一
      registered_residence_name: '', // 户口所在地名称，唯一
      household_immigration: 0, // 户籍迁入(0-否,1-是)
      household_immigration_date: '', // 户籍迁入日期
      migrant_children: 0, // 随迁子女(0-否,1-是)
    },
    // 下拉选项及下标
    cityOptions: [],
    cityIndex: null,
    countyOptions: [],
    countyIndex: null,
    registrationPointOptions: [],
    registrationPointIndex: null,
    graduateTypeOptions: [],
    graduateTypeIndex: null,
    graduateSchoolOptions: [],
    graduateSchoolIndex: null,
    studySchoolOptions: [],
    studySchoolIndex: null,
    registrationAuthorityOptions: [],
    registrationAuthorityIndex: null,
    registeredResidenceOptions: [],
    registeredResidenceIndex: null,
    householdOptions: ['否', '是'], // 户籍迁入选择
    householdIndex: 0, // 默认“否”,
    migrantChildrenIndex:0,//默认“否”

    // 展示户籍迁入相关信息的字段
    isShowHouseholdInfo: false,

    // 语音相关
    recordedText: null,
    recording: false,
    recordFilePath: '',
    buttonText: '开始录音',
    editableContent:''
  },

  onLoad() {
    // 加载各个下拉框选项数据
    const cityPromise = tools.fetchOptions3('/city/list', 'cityOptions', this);
    const countyPromise = tools.fetchOptions('/gaokao/GkCounty/all', 'countyOptions', this);
    const regPointPromise = tools.fetchOptions('/gaokao/GkCounty/all', 'registrationPointOptions', this);
    const gradTypePromise = tools.fetchOptions('/gaokao/GkGraduateType/all', 'graduateTypeOptions', this);
    const gradSchoolPromise = tools.fetchOptions2('/gaokao/GkMiddleSchool/all', 'graduateSchoolOptions', this);
    const studySchoolPromise = tools.fetchOptions2('/gaokao/GkMiddleSchool/all', 'studySchoolOptions', this);
    const regAuthorityPromise = tools.fetchOptions2('/gaokao/GkRegistrationAuthority/all', 'registrationAuthorityOptions', this);
    const regResidencePromise = tools.fetchOptions2('/gaokao/GkRegisteredResidence/all', 'registeredResidenceOptions', this);
    
    //所有选项框加载完成后，加载本地数据，对index进行更新
    Promise.all([cityPromise, countyPromise, regPointPromise, gradTypePromise, gradSchoolPromise, studySchoolPromise, regAuthorityPromise, regResidencePromise])
      .then(() => {
        // 加载本地存储的学籍信息（如有）
        const storedInfo = wx.getStorageSync('gk_academic_info');
        if (storedInfo) {
          this.setData({ gk_academic_info: storedInfo });
          // 根据存储的各字段 id 查找下标，更新下拉框默认选中
          this.updateIndexById(storedInfo);
        }
      })
      .catch(err => {
        console.error('加载选项数据失败:', err);
      });
  },

  updateIndexById(data){
    // 根据存储的各字段 id/code/name 查找下标，更新下拉框默认选中
    this.setData({
      cityIndex: tools.findIndexByCode2(this.data.cityOptions, data.city_code),
      countyIndex: tools.findIndexByCode(this.data.countyOptions, data.county_code),
      registrationPointIndex: tools.findIndexByCode(this.data.registrationPointOptions, data.registration_point_code),
      graduateTypeIndex: tools.findIndexByCode(this.data.graduateTypeOptions, data.graduate_type_id),
      graduateSchoolIndex: tools.findIndexByName(this.data.graduateSchoolOptions, data.graduate_school_name),
      studySchoolIndex: tools.findIndexByName(this.data.studySchoolOptions, data.study_school_name),
      registrationAuthorityIndex: tools.findIndexByName(this.data.registrationAuthorityOptions, data.registration_authority),
      registeredResidenceIndex: tools.findIndexByCode(this.data.registeredResidenceOptions, data.registered_residence_code),
      householdIndex: data.household_immigration === 1 ? 1 : 0
    });
    this.updateHouseholdInfo(data.household_immigration);
  },
  
  updateHouseholdInfo(name){
    // 根据字段值选择是否重置选项，以及是否展示相关信息
    if(name == 1){
      this.setData({
        isShowHouseholdInfo: true
      })
    }else{
      this.setData({
        isShowHouseholdInfo: false,
        'gk_academic_info.household_immigration_date': '',
        'gk_academic_info.migrant_children': 0
      })
    }
  },

  // 输入框回调
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`gk_academic_info.${field}`]: e.detail.value });
  },

  // 下拉选择回调：更新相应字段下标和值（选项的 id 或 code 或 name）
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const index = e.detail.value;
    let valueId = '';
    // 根据 field 区分不同选项来源
    if (field === 'city_code') {
      valueId = this.data.cityOptions[index].id;
      this.setData({ cityIndex: index });
    } else if (field === 'county_code') {
      valueId = this.data.countyOptions[index].code;
      this.setData({ countyIndex: index });
    } else if (field === 'registration_point_code') {
      valueId = this.data.registrationPointOptions[index].code;
      this.setData({ registrationPointIndex: index });
    } else if (field === 'graduate_type_id') {
      valueId = this.data.graduateTypeOptions[index].code;
      this.setData({ graduateTypeIndex: index });
    } else if (field === 'graduate_school_code') {
      valueId = this.data.graduateSchoolOptions[index].code;
      // 更新毕业中学名称
      this.setData({
        'gk_academic_info.graduate_school_name': this.data.graduateSchoolOptions[index].name
      });
      this.setData({ graduateSchoolIndex: index });
    } else if (field === 'study_school_code') {
      valueId = this.data.studySchoolOptions[index].code;
      // 更新就读中学名称
      this.setData({
        'gk_academic_info.study_school_name': this.data.studySchoolOptions[index].name
      });
      this.setData({ studySchoolIndex: index });
    } else if (field === 'registration_authority') {
      valueId = this.data.registrationAuthorityOptions[index].name;
      this.setData({ registrationAuthorityIndex: index });
    } else if (field === 'registered_residence_code') {
      valueId = this.data.registeredResidenceOptions[index].code;
      // 更新户口所在地名称
      this.setData({
        'gk_academic_info.registered_residence_name': this.data.registeredResidenceOptions[index].name
      });
      this.setData({ registeredResidenceIndex: index });
    } else if(field === 'migrant_children'){
      valueId = index;
      this.setData({migrantChildrenIndex:index})
    }
    // 更新对应字段值
    this.setData({ [`gk_academic_info.${field}`]: valueId });
  },

  // 日期选择回调
  handleDateChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`gk_academic_info.${field}`]: e.detail.value });
  },

  // “户籍迁入”下拉框改变时，动态显示或隐藏户籍相关输入框
  handleHouseholdChange(e) {
    const index = e.detail.value;
    this.setData({
      householdIndex: index,
      'gk_academic_info.household_immigration': index
    });
    this.updateHouseholdInfo(index)
  },

  // 提交学籍信息，并跳转到考试报考信息填写页面（chengkao_page3）
  handleSubmit() {
    const data = this.data.gk_academic_info;
    // 检查信息是否有修改
    // 待检查字段对照表
    const fieldsToCheck = [
      'city_code',
      'county_code',
      'registration_point_code',
      'graduate_type_id',
      'graduate_school_name',
      'graduate_class',
      'study_school_name',
      'study_class',
      'registration_authority',
      'registered_residence_code',
      'household_immigration',
      'household_immigration_date',
      'migrant_children'
    ];
    // 获取本地信息
    const storedInfo = wx.getStorageInfoSync("gk_academic_info");
    // 检查信息是否发生更改
    if(tools.checkDataChanged(data,storedInfo,fieldsToCheck,)){
      // 可在此添加字段校验
      // 调用后端接口更新信息（接口地址根据实际情况调整）
      const idNumber = wx.getStorageSync('base_candidate_info').id_number;
      const postData = {
        idNumber: idNumber,
        cityCode: data.city_code,
        countyCode: data.county_code,
        registrationPointCode: data.registration_point_code,
        graduateTypeId: data.graduate_type_id,
        // graduateSchoolCode: data.graduate_school_code,
        graduateSchoolName: data.graduate_school_name,
        graduateClass: data.graduate_class,
        // studySchoolCode: data.study_school_code,
        studySchoolName: data.study_school_name,
        studyClass: data.study_class,
        registrationAuthority: data.registration_authority,
        registeredResidenceCode: data.registered_residence_code,
        // registeredResidenceName: data.registered_residence_name,
        householdImmigration: data.household_immigration,
        householdImmigrationDate: data.household_immigration_date,
        migrantChildren: data.migrant_children
      };
      http.post("/gaokao/CandidateRegistration/upsert", postData).then(res => {
        if (res.data.code === 200) {
          // 更新本地存储
          wx.setStorageSync('gk_academic_info', this.data.gk_academic_info);
          wx.showToast({ title: '学籍信息更新成功', duration: 2000 });
          wx.navigateTo({ url: '/pages/gaokao/gaokao_page3/gaokao_page3' });
        }
      }).catch(err => {
        console.error('学籍信息更新失败:', err);
        wx.showToast({ title: '学籍信息更新失败', icon: 'none', duration: 2000 });
      });
    }else {
      // 未发生更改，直接跳转页面
      wx.navigateTo({ url: '/pages/gaokao/gaokao_page3/gaokao_page3' });
    }
  },

  // 语音功能
  // 录音功能区
  /**
   * 切换录音状态（开始/停止录音）
   */
  toggleRecording() {
    if (this.data.recording) {
      this.setData({ recording: false });
      const recorderManager = wx.getRecorderManager();
      recorderManager.stop();
      recorderManager.onStop((res) => {
        wx.setStorageSync('recordPath', res.tempFilePath);
        this.setData({ recordFilePath: res.tempFilePath });
        this.setData({ buttonText: '开始录音' });
      });
    } else {
      tools.checkRecordPermission().then(()=>{
        this.setData({ recording: true, buttonText: '停止录音' });
        // 开始录音
        const recorderManager = wx.getRecorderManager();
        recorderManager.start({
          format: 'wav',
          duration: 60000,
          sampleRate: 44100,
          numberOfChannels: 1,
          encodeBitRate: 96000
        });
      })
      .catch(() => {
        wx.showToast({ title: err.message, icon: 'none' });
      });
    }
  },
  uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
      wx.showToast({ title: '请先录制录音', icon: 'none' });
      return;
    }
    const filePath = this.data.recordFilePath;
    // 调用后端识别接口
    http.asr(filePath).then(res =>{
      console.log("语音识别成功，文本如下：")
      console.log(res);
      // 根据返回的文本信息，提取其中的信息
      this.setData({ editableContent: res });
      // 调用后端的提取接口
      const postData = { "text": res };
      http.gkExtract(postData).then(res =>{
        // 处理提取后的结果
        console.log("提取后的结果，如下：")
        console.log(res)
        this.updateIdAndIndex(res.data)
      }).catch(err => {
        // 提取失败
        console.log('无法解析识别结果：', err);
        console.log('接收到的原始返回数据：', err.data);
      });
    }).catch(err =>{
      // 语音识别失败
      console.log('语音识别失败：', err);
      wx.showToast({ title: '录音识别失败', icon: 'none', duration: 2000 });
    })
  },
  // 获取了语音识别返回的结果后，对id和index进行更新
  updateIdAndIndex(dataFields){
    /* 对于一些字段需要进行特殊的处理：
    * "graduate_school","study_school",先名字进行赋值，随后更新对应的index
    * 'registered_residence',获取name，然后获取对应的code，然后更新index
    * "registration_authority"，获取name，获取对用index
    **/
    // 可以直接赋值的字段
    const fields = ["graduate_class", "study_class","household_immigration", "household_immigration_date", "migrant_children", "graduate_school_name", "study_school_name", "registration_authority"]
    // 需要进行映射的字段
    // 名称和id的映射,key为code字段，value为name字段
    const idFields={
        city_code: 'city',
        county_code: 'county',
        registration_point_code: 'registration_point',
        graduate_type_id: 'graduate_type',
        // graduate_school_name: 'graduate_school_name',
        // study_school_name: 'study_school_name',
        // registration_authority: 'registration_authority',
        registered_residence_code: 'registered_residence_name',
    }
    // 名称和选项映射的字段
    const arrayFields = {
      city_code: 'cityOptions',
      county_code: 'countyOptions',
      registration_point_code: 'registrationPointOptions',
      graduate_type_id: 'graduateTypeOptions',
      // graduate_school_name: 'graduateSchoolOptions',
      // study_school_name: 'studySchoolOptions',
      // registration_authority: 'registrationAuthorityOptions',
      registered_residence_code: 'registeredResidenceOptions'
    }
    // 根据结果给字段直接赋值
    fields.forEach(key =>{
        if(!dataFields[key].includes("未知")){
            this.setData({
                [`gk_academic_info.${key}`]:dataFields[key]
            })
        }
    })
    // 赋值后检查户籍迁入字段间的相关信息
    this.updateHouseholdInfo(this.data.gk_academic_info.household_immigration);

    // 根据名字赋值code
    Object.entries(idFields).forEach(([key,value]) =>{
        // 通过两个字典的映射获取对应的值，查询id随后进行赋值
        if(!dataFields[value].includes("未知")){
          // 对考点盟市进行单独处理
          if(key == "city_code"){
            this.setData({
              [`gk_academic_info.${key}`]:tools.findIdByName2(this.data[arrayFields[key]],dataFields[key])
            })
          }
          this.setData({
            [`gk_academic_info.${key}`]:tools.findCodeByName(this.data[arrayFields[key]],dataFields[key])
          })
        }
    })
    //更新下标
    this.updateIndexById(this.data.gk_academic_info)
  },
});
